%%%-------------------------------------------------------------------
%%% @author mirahs(2892727493@qq.com)
%%% @doc
%%%     网络通讯监听服务
%%% @end
%%%-------------------------------------------------------------------
-module(net_tcp_listen_srv).

-behaviour(gen_server).

-export([start_link/0]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

-include("common.hrl").
-include("env.hrl").
-include("net.hrl").


%%%===================================================================
%%% Spawning and gen_server implementation
%%%===================================================================

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).


init([]) ->
    Port = env_mgr:get(?ENV_NET_TCP_PORT),
    case gen_tcp:listen(Port, ?NET_TCP_OPTIONS) of
        {ok, ListenSocket} ->
            ?ECHO("正在启动[~w]", [?MODULE]),
            Cores = util_sys:core_count(),
            start_acceptor(ListenSocket, 1, Cores),
            ?ECHO("完成启动[~w] 端口:~w", [?MODULE, Port]),
            {ok, undefined};
        {error, Reason}->
            ?ERR("监听端口[~w]:~w 错误:~n~p", [?MODULE, Port, Reason]),
            {stop, Reason}
    end.

handle_call(_Request, _From, State) ->
    {reply, ok, State}.

handle_cast(_Request, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.


%%%===================================================================
%%% Internal functions
%%%===================================================================

start_acceptor(_ListenSocket, Idx, Num) when Idx > Num-> ok;
start_acceptor(ListenSocket, Idx, Num)->
    net_tcp_accepter_sup:start_child(ListenSocket, Idx),
    start_acceptor(ListenSocket, Idx + 1, Num).
